/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 * @version 1.0
 */
package shop.controller.manage.activity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import shop.core.BaseController;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.services.common.Kcrelation;
import shop.services.manage.activity.ActivityService;
import shop.services.manage.activity.bean.Activity;
import shop.services.manage.activitycharge.ActivitychargeService;
import shop.services.manage.activitycharge.bean.Activitycharge;
import shop.services.manage.kcrelation.KcrelationService;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名称：ActivityAction
 * @创建人：Ltz
 * @创建时间：2017-08-29 下午19:53:49
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/manage/activity/")
public class ActivityAction extends BaseController<Activity> {
    private static final Logger logger = LoggerFactory.getLogger(ActivityAction.class);
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ActivitychargeService activitychargeService;
    @Autowired
    private KcrelationService kcrelationService;
    @Autowired
    private UserService userService;

    private static final String page_toList = "/manage/activity/activityList";
    private static final String page_toAdd = "/manage/activity/activityAdd";
    private static final String page_toEdit = "/manage/activity/activityEdit";
    private static final String page_toStoreList = "/manage/activity/activityCacheList";
    private static final String page_toChargeDetail = "/manage/activity/activityCacheDetail";
    private static final String page_toPictureList = "/manage/activitypicture/activitypictureList";
    private static final String page_toActivityDetail = "/manage/activity/activityDetail";

    public ActivityService getService() {
        return activityService;
    }

    private ActivityAction(){
        super.page_toList = page_toList;
        super.page_toAdd = page_toAdd;
        super.page_toEdit = page_toEdit;
    }

    /**
     * 查询跳转到编辑活动页面
     *
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toEdit")
    public String toEdit(@ModelAttribute("e") Activity e, ModelMap model) throws Exception {
        e = activityService.selectOne(e);
        model.addAttribute("e", e);
        return page_toEdit;
    }

    /**
     * 跳转到门店列表页面
     *
     * @return
     */
    @RequestMapping("toStoreList")
    public String toStoreList() {
        return page_toStoreList;
    }

    /**
     * 跳转到费用信息页面
     *
     * @return
     */
    @RequestMapping("toChargeDetail")
    public String toChargeDetail(@ModelAttribute("e") Activitycharge e, ModelMap model) throws Exception {
        e = activitychargeService.selectOne(e);
        model.addAttribute("e", e);
        return page_toChargeDetail;
    }


    /**
     * 跳转到照片列表页面
     *
     * @return
     */
    @RequestMapping("toPictureList")
    public String toPictureList() {
        return page_toPictureList;
    }

    /**
     * 跳转到查看活动页面
     *
     * @return
     */
    @RequestMapping("toActivityDetail")
    public String toActivityDetail(@ModelAttribute("e") Activity e, ModelMap model) throws Exception {
        e = activityService.selectOne(e);
        model.addAttribute("e", e);
        return page_toActivityDetail;
    }



    /**
     * 查询活动列表（发布）
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @RequestMapping("loadIssueData")
    @ResponseBody
    public PagerModel loadIssueData(HttpServletRequest request, Activity e) {
        int offset = 0;
        int pageSize = 10;
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = activityService.selectIssuePageList(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }


    /**
     * 查询活动列表（参与）
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @RequestMapping("loadJoinData")
    @ResponseBody
    public PagerModel loadJoinData(HttpServletRequest request, Activity e) {
        int offset = 0;
        int pageSize = 10;
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = activityService.selectJoinPageList(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }


    /**
     * 品牌商发布活动
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "insertActivity", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertActivity(Activity activity) throws Exception {
        jsonResult = new JSONResult();
        Kcrelation kcrelation = kcrelationService.selectByBrandID(activity.getBrandID());//查询绑定关系
        if(kcrelation!=null){//判断品牌商是否有绑定KA经理
            activity.setKaID(kcrelation.getKaID());//插入kaID
        }else{
            jsonResult.setMessage("该品牌商未绑定KA经理，不能发布活动！");//返回信息
            jsonResult.setSuccess(false);
            return jsonResult;
        }
        Activity rs=new Activity();
        rs.setKaName(activity.getName());
        rs=activityService.selectOne(rs);
        if(rs==null) {
            activity.setKaName(activity.getName());
            activity.setKaDemand(activity.getDemand());
            activity.setKaStarTime(activity.getStarTime());
            activity.setKaEndTime(activity.getEndTime());
            activity.setKaBudge(activity.getBudge());
            activity.setKaPicture(activity.getPicture());
            activity.setKaProductName(activity.getProductName());
            activity.setKaProductCode(activity.getProductCode());//备份KA经理活动信息
            activity.setInsertStatus("1");
            activity.setUpdateStatus("0");
            activity.setStoreMember(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date2 = sdf.format(new Date());//格式化日期
            if (date2.compareTo(activity.getStarTime()) <= 0) {//判断活动是否提前一天发布
                activityService.insert(activity);
                User ka = new User();
                ka.setId(kcrelation.getKaID());
                ka = userService.selectOne(ka);//查询绑定KA经理信息
                //发送微信模版消息
                Map<String, String> msgParam = new HashMap<>();
                msgParam.put("first", "尊敬的" + ka.getNickname() + "，您有一条新的活动信息请及时查收！");
                msgParam.put("keyword1", activity.getKaName());
                msgParam.put("keyword2", activity.getKaStarTime() + " 至 " + activity.getKaEndTime());
                msgParam.put("keyword3", "——");
                msgParam.put("keyword4", activity.getKaDemand());
                msgParam.put("remark", "请登录平台查看活动信息");
                WxMsgUtil.sendActivityStatusMsg(msgParam, systemManager.getAccessToken(), ka.getOpenID());
                User user = new User();
                user.setId(activity.getBrandID());
                user = userService.selectOne(user);//查询发布活动的品牌商信息
                user.setIssueNumber(user.getIssueNumber() + 1);
                userService.update(user);//更新品牌商发布活动次数
                return jsonResult;
            } else {
                jsonResult.setMessage("请提前一天发布活动！");//返回信息
                jsonResult.setSuccess(false);
                return jsonResult;
            }
        }else{
            jsonResult.setMessage("该活动名称已存在，请勿重复添加！");//返回信息
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }

    /**
     * 查询活动列表
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @Override
    @RequestMapping("loadData")
    @ResponseBody
    public PagerModel loadData(HttpServletRequest request, Activity e) {
        int offset = 0;
        int pageSize = 10;
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = getService().selectPageListFist(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 编辑活动
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateActivityJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateActivityJson(Activity activity) throws Exception {
        jsonResult = new JSONResult();
        activity.setUpdateStatus("1");
        activityService.update(activity);
        return jsonResult;
    }

    /**
     * 批量删除活动
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "deleteActivities", method = RequestMethod.POST)
    @ResponseBody
    public String deletesJson(HttpServletRequest request, @RequestParam(value = "ids[]") String[] ids,Activity activity) throws Exception {
        getService().deletes(ids);
        for(int i=0;i<ids.length;i++){
            activity.setId(ids[i]);
            activity=activityService.selectOne(activity);
            User user=new User();
            user.setId(activity.getBrandID());
        }
        return "success";
    }

    /**
     * 查询单个活动
     * @param activity
     * @return
     */
    @RequestMapping(value = "selectActivityDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectActivityDetail(Activity activity) {
        activity = activityService.selectOne(activity);
        jsonResult = new JSONResult();
        jsonResult.setData(activity);
        return jsonResult;
    }

}
